package com.pj.wisdomlogistics.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.mvp.contract.ApplyCarContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.ApplyCarPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.view.AutoRadioGroup;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.sjy.imagepicker.ImageViewerActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class ApplyCarActivity extends MvpActivity<ApplyCarPresenter> implements ApplyCarContract.View, OnDateSetListener {

    @BindView(R.id.rb_cause_1)
    RadioButton mRbCause1;
    @BindView(R.id.rb_cause_2)
    RadioButton mRbCause2;
    @BindView(R.id.rb_cause_3)
    RadioButton mRbCause3;
    @BindView(R.id.rg_declare_cause)
    AutoRadioGroup mRgDeclareCause;
    @BindView(R.id.et_destination)
    EditText mEtDestination;
    @BindView(R.id.et_detail_reason)
    EditText mEtDetailReason;
    @BindView(R.id.et_car_count)
    EditText mEtCarCount;
    @BindView(R.id.et_car_contact)
    EditText mEtCarContact;
    @BindView(R.id.et_car_tel)
    EditText mEtCarTel;
    @BindView(R.id.tv_apply_dept)
    TextView mTvApplyDept;
    @BindView(R.id.tv_apply_dept_contacts)
    TextView mTvApplyDeptContacts;
    @BindView(R.id.tv_apply_dept_call)
    TextView mTvApplyDeptCall;
    @BindView(R.id.tv_apply_dept_phone)
    TextView mTvApplyDeptPhone;
    @BindView(R.id.et_car_time)
    EditText mEtCarTime;
    @BindView(R.id.rg_bd)
    AutoRadioGroup mRgBd;
    @BindView(R.id.rb_place_zf)
    RadioButton mRbPlaceZf;
    @BindView(R.id.rb_place_shy)
    RadioButton mRbPlaceShy;


    long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;
    private int currentCause;
    private int isBd;

    @Override
    public void onError(String errorMsg) {
        dismissProgressDialog();
        CustomToast.showToast(this , errorMsg , 1000);
    }

    @Override
    public void onSuccess(int id) {
        dismissProgressDialog();
        Intent mIntent = new Intent(this, SuccessActivity.class);
        mIntent.putExtra(Cons.CarInfo.CAR_ID, id);
        startActivity(mIntent);
        ActivityManagerUtil.create().finishActivity();
    }

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        mTvApplyDept.setText(MyApplication.user.getDeptName());
        mTvApplyDeptContacts.setText(MyApplication.user.getName());
        mTvApplyDeptCall.setText(MyApplication.user.getTelphone());
        mTvApplyDeptPhone.setText(MyApplication.user.getMobile());

        mRgDeclareCause.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb_cause_1:
                        currentCause = 1;
                        break;
                    case R.id.rb_cause_2:
                        currentCause = 0;
                        break;
                    case R.id.rb_cause_3:
                        currentCause = 2;
                        break;
                }
            }
        });


        mRgBd.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                switch (checkedId) {
                    case R.id.rb_bd_1:
                        isBd = 0;
                        break;
                    case R.id.rb_bd_2:
                        isBd = 1;
                        break;
                }
            }
        });

        List<Integer> mList = new ArrayList<>();
        mList.add(R.drawable.rule);
        mList.add(R.drawable.rule1);

        Intent intent = new Intent(this, ImageActivity.class);
        intent.putExtra(ImageViewerActivity.CURRENT_POS, 0);
        intent.putIntegerArrayListExtra(ImageViewerActivity.IMAGE_PATH_LIST, (ArrayList<Integer>) mList);
        startActivity(intent);
    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_apply_car;
    }

    @Override
    public boolean isApplyEventBus() {
        return false;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {

    }


    @OnClick({R.id.iv_back, R.id.tv_send, R.id.et_car_time , R.id.iv_remark})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ActivityManagerUtil.create().finishActivity();
                break;
            case R.id.tv_send:
                String detailReason = mEtDetailReason.getText().toString().trim();
                String carCount = mEtCarCount.getText().toString().trim();
                String carContact = mEtCarContact.getText().toString().trim();
                String carTel = mEtCarTel.getText().toString().trim();
                String carTime = mEtCarTime.getText().toString().trim();
                String destination = mEtDestination.getText().toString().trim();
                String place = mRbPlaceZf.isChecked() ? "1" : "2";

                if (!checkInfo(detailReason, carCount, carContact, carTel, carTime, destination))
                    return;

                mPresenter.submitCarApply(
                        MyApplication.userID,
                        MyApplication.user.getName(),
                        MyApplication.user.getMobile(),
                        MyApplication.user.getDept_id(),
                        MyApplication.user.getDeptName(),
                        MyApplication.user.getTelphone(),
                        currentCause + "",
                        destination,
                        detailReason,
                        carCount,
                        carTime,
                        carContact,
                        carTel,
                        isBd,
                        place
                );
                showProgressDialog();

                break;
            case R.id.et_car_time:
                TimePickerDialog mDialogAll = new TimePickerDialog.Builder()
                        .setCallBack(this)
                        .setCancelStringId("取消")
                        .setSureStringId("确认")
                        .setTitleStringId("用车时间")
                        .setYearText("年")
                        .setMonthText("月")
                        .setDayText("日")
                        .setHourText("时")
                        .setMinuteText("分")
                        .setCyclic(false)
                        .setMinMillseconds(isBd == 0 ? System.currentTimeMillis() : System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000)
                        .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                        .setCurrentMillseconds(System.currentTimeMillis())
                        .setThemeColor(getResources().getColor(R.color.text_blue))
                        .setType(Type.ALL)
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.text_gray))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.text_normal))
                        .setWheelItemTextSize(12)
                        .build();
                mDialogAll.show(getSupportFragmentManager(), "all");
                break;
            case R.id.iv_remark:
                ImageView mImageView = new ImageView(this);
                mImageView.setImageResource(R.drawable.note2);
                mImageView.setScaleType(ImageView.ScaleType.FIT_XY);

                AlertDialog.Builder  builder  =  new AlertDialog.Builder(this);
                AlertDialog ad = builder.create();
                ad.setCanceledOnTouchOutside(true);
                ad.setView(mImageView);
                ad.show();
                break;
        }
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        mEtCarTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(millseconds)));

    }

    private boolean checkInfo(
            String detailReason,
            String carCount,
            String carContact,
            String carTel,
            String carTime,
            String destination) {

        if (TextUtils.isEmpty(detailReason) ||
                TextUtils.isEmpty(carCount) ||
                TextUtils.isEmpty(carContact) ||
                TextUtils.isEmpty(carTel) ||
                TextUtils.isEmpty(destination)) {
            CustomToast.showToast(this , "请将信息填写完整" , 1000);
            return false;
        }

        if(Integer.parseInt(carCount) <= 0 ){
            CustomToast.showToast(this , "请输入正确的用车人数" , 1000);
            return false;
        }

//        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        try {
//            Date mDate = mSimpleDateFormat.parse(carTime);
//            Date mDateNow = new Date(System.currentTimeMillis());
//
//            Calendar mCalendar1 = Calendar.getInstance();
//            mCalendar1.setTime(mDate);
//
//            Calendar mCalendar2 = Calendar.getInstance();
//            mCalendar2.setTime(mDateNow);
//
//            if ((mCalendar1.get(Calendar.DAY_OF_MONTH) - mCalendar2.get(Calendar.DAY_OF_MONTH) < 1
//                    && mCalendar1.get(Calendar.MONTH) == mCalendar2.get(Calendar.MONTH))
//                    || mCalendar1.get(Calendar.MONTH) < mCalendar2.get(Calendar.MONTH)) {
//                CustomToast.showToast(this , "请提前一天申请用车" , 1000);
//                return false;
//            }
//
//        } catch (ParseException mE) {
//            mE.printStackTrace();
//        }

        return true;
    }


}
